<?php

namespace App\Http\Controllers\Api;

use App\Events\addLog;
use App\Http\Controllers\Controller;
use App\Models\School;
use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Mockery\Exception;

class ExcelController extends Controller
{


    /**
     * @param Request $request
     * 导出Excel
     */
    public function exportStudent(Request $request)
    {
        $school_id = $request->get('school_id');
        if ($school_id == '0') {
            $school_name = '所有幼儿报名信息';
            event(new addLog(Auth::user(),'导出'.$school_name));
        } else {
            $school_name = School::query()->where('school_code', $school_id)->first()->school_name;
            event(new addLog(Auth::user(),'导出'.$school_name.'报名信息'));
        }
        \Excel::create($school_name, function ($excel) use ($school_id) {
            $student = $this->getStudent($school_id);
            $excel->sheet('报名信息', function ($sheet) use ($student) {
                $sheet->rows($student);
            });
        })->export('xls');

    }
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * 导入Excel
     */
    public function importStudent(Request $request)
    {
        $excel = $request->file('file');
        $extension = $excel->getClientOriginalExtension();
        $filePath = $excel->move(storage_path('app/public/excel'), 'excel.' . $extension);
        $name = $excel->getClientOriginalName();
        $extension = $filePath->getExtension();
        $filePath = $filePath->getPath() . '/excel.' . $extension;
        $errors = [];

        \Excel::load($filePath, function ($reader) use (&$errors) {
            $data = $reader->getSheet(0)->toArray();
            foreach ($data as $key => $value) {
                if ($key > 0) {
                    try {
                        $stundents = Student::query()->where('id_code', $value[2])->first();
                        $entity_id = $stundents->entity_id;
                        $stundents = Student::query()->where('entity_id', $entity_id)->get();
                        $school = School::query()->where('school_code', $value[0])->first();
                        if (!$stundents) {
                            throw new \Exception('第' . ($key + 1) . '行身份证号错误！');
                        } else {
                            foreach ($stundents as $stundent){
                                $stundent->is_enroll = 1;
                                $school->is_import = 1;
                                $school->save();
                                if ($stundent->sex == '男') {
                                    $stundent->sex = 0;
                                } else {
                                    $stundent->sex = 1;
                                }
                                if (!$stundent->save()) {
                                    throw new \Exception('第' . ($key + 1) . '行保存失败！');
                                }
                            }
                        }
                    } catch (Exception $e) {
                        $errors[] = $e->getMessage();
                    }
                }
            }
        });
        if (count($errors) > 0) {
            return response($errors, 500);
        } else {
            event(new addLog(Auth::user(),'导入'.$name.'报名信息'));
            return response(['导入成功！'], 200);
        }
    }

    /**
     * @param $school_id
     * @return array
     * 查询返回家庭报名占名额的孩子，字段为first_kid 值为1
     */
    public function getStudent($school_id)
    {
        $stundentArr = [];
        $stundentArr[] = [
            'StudentName',
            'Sex',
            'IDCode',
            'ZySchoolCode',
            'ZySchoolName',
            'Section',
            'Twins'
        ];
        if ($school_id == '0') {
            $stundents = Student::query()->where('first_kid','=','1')->get();

        } else {
            $stundents = Student::query()->where('first_kid','1')
                ->where('school_id', $school_id)->get();
        }
        foreach ($stundents as $key => $value) {
            $school = $value->school;
            $stundentArr[] = [
                $value->name,
                $value->sex,
                " " . $value->id_code,
                $school->school_code,
                $school->school_name,
                $value->section_id,
                $value->twins
            ];
        }
        return $stundentArr;
    }

}
